<div class="box box-primary" id="control">
    <div class="box-header">
        <div class="col-sm-9" style="padding-top:8px;">
            <i class="glyphicon glyphicon-lock">&nbsp;</i>
            <h1 class="box-title" style="font-weight:bold;" id="id_h1_page_title"></h1>
        </div>
        <div class="col-sm-1" style="padding-top:2px;">
          <button id="id_btn_reset" class="btn btn-sm btn-danger btn-del"><i class="fa fa-trash"></i><span id="id_btn_span_reset">Reset</span></button>
        </div>
        <div class="col-sm-2" style="font-size:16px;padding-top:8px;">
            <a id="id_a_official_doc" target="_blank" href="https://www.ventoy.net/en/plugin_password.html"><span class="fa fa-link"></span><span id="id_span_official_doc">官网文档</span></a>
        </div>
    </div>
    <legend></legend>
    
    <div class="box-body">
      <div class="nav-tabs-custom">
        <ul class="nav nav-tabs" id="id_tab_password">
            <li class=""><a href="#tab_0" data-toggle="tab" aria-expanded="false" style="font-weight:bold" >password</a></li>
            <li class=""><a href="#tab_1" data-toggle="tab" aria-expanded="false"  style="font-weight:bold">password_legacy</a></li>
            <li class=""><a href="#tab_2" data-toggle="tab" aria-expanded="false"  style="font-weight:bold">password_uefi</a></li>
            <li class=""><a href="#tab_3" data-toggle="tab" aria-expanded="false"  style="font-weight:bold">password_ia32</a></li>
            <li class=""><a href="#tab_4" data-toggle="tab" aria-expanded="false"  style="font-weight:bold">password_aa64</a></li>
            <li class=""><a href="#tab_5" data-toggle="tab" aria-expanded="false"  style="font-weight:bold">password_mips</a></li>
        </ul>
      </div>


      <div class="box box-primary box-solid">
        <div class="box-header with-border">
          <h3 class="box-title" style="font-size: 14px;font-weight: bold;">Common Password
            <span id="id_span_desc_cn"> —— 通用密码</span></h3>
          <div class="box-tools pull-right">
            <button class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
          </div><!-- /.box-tools -->
        </div><!-- /.box-header -->
        <div class="box-body no-padding">
          <table id="id_common_pwd" class="table table-bordered">
            <thead>
              <tr>
                <th id="id_th_pwd_opt" style="width: 10%;"></th>
                <th id="id_th_pwd_set" style="width: 40%;"></th>
                <th id="id_th_pwd_operate" style="width: 10%;"></th>
                <th id="id_th_pwd_notes" style="width: 30%;"></th>
              </tr>
            </thead>
            <tbody>
            </tbody>
          </table>
        </div>
      </div>


      <div class="box box-primary box-solid">
        <div class="box-header with-border">
          <h3 class="box-title" style="font-size: 14px;font-weight: bold;">Menu Password
            <span id="id_span_desc_cn"> —— 菜单密码</span></h3>
          <div class="box-tools pull-right">
            <button class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
          </div><!-- /.box-tools -->
        </div><!-- /.box-header -->
        <div class="box-body no-padding">
          <table id="id_pwd_tbl" class="table table-bordered">
            <thead>
              <tr>
                <th style="width: 2%;">#</th>
                <th id="id_th_pwd_type" style="width: 5%;"></th>
                <th id="id_th_pwd_path" style="width: 45%;"></th>
                <th id="id_th_status" style="width: 5%;"></th>
                <th id="id_th_pwd_pwd" style="width: 35%;"></th>
                <th id="id_th_operation" style="width: 10%;"></th>
              </tr>
            </thead>
            <tbody>
            </tbody>
          </table>
        </div>
      </div>
      <br/><br/>


    </div>
</div>
<script type="text/javascript">
    
  function VtoyPageLanguageChange(newlang) {
    VtoyCommonChangeLanguage(newlang);
    $('h1[id=id_h1_page_title]').text(g_vtoy_cur_language.STR_PLUG_PASSWORD);

    $("span[id=id_span_file_exist]").each(function(){
        $(this).text(g_vtoy_cur_language.STR_FILE_EXIST);
    });
    $("span[id=id_span_file_nonexist]").each(function(){
        $(this).text(g_vtoy_cur_language.STR_FILE_NONEXIST);
    });
    $("span[id=id_span_file_fuzzy]").each(function(){
        $(this).text(g_vtoy_cur_language.STR_FILE_FUZZY);
    });

    $("span[id=id_span_dir_exist]").each(function(){
        $(this).text(g_vtoy_cur_language.STR_DIR_EXIST);
    });
    
    $("span[id=id_span_dir_nonexist]").each(function(){
        $(this).text(g_vtoy_cur_language.STR_DIR_NONEXIST);
    });

    $("span[id=id_span_edit]").each(function(){
        $(this).text(' ' + g_vtoy_cur_language.STR_EDIT);
    });

    $("span[id=id_span_clear]").each(function(){
        $(this).text(' ' + g_vtoy_cur_language.STR_CLEAR);
    });

    if (newlang === 'en') {
      $('#id_th_pwd_path').text('Absolute Path');
      $('#id_th_pwd_pwd').text('Password');
      $('#id_th_pwd_type').text('Type');
      $("th[id=id_th_pwd_opt]").text('Option');
      $("th[id=id_th_pwd_set]").text('Setting');
      $("th[id=id_th_pwd_operate]").text('Operation');
      $("th[id=id_th_pwd_notes]").text('Notes');

      $("span[id=id_span_desc_cn]").each(function(){
          $(this).hide();
      });
      $("span[id=id_span_desc_en]").each(function(){
          $(this).show();
      });
    } else {
      $('#id_th_pwd_path').text('绝对路径');
      $('#id_th_pwd_pwd').text('密码');
      $('#id_th_pwd_type').text('类型');
      $("th[id=id_th_pwd_opt]").text('选项');
      $("th[id=id_th_pwd_set]").text('设置');
      $("th[id=id_th_pwd_operate]").text('操作');
      $("th[id=id_th_pwd_notes]").text('说明');
      $("span[id=id_span_desc_en]").each(function(){
          $(this).hide();
      });
      $("span[id=id_span_desc_cn]").each(function(){
          $(this).show();
      });
    }
  }
  
  function format_password(pwd, type) {
    if (type === 0) {
      return 'txt#' + pwd;
    } else if (type === 1) {
      return 'md5#' + md5(pwd);
    } else {
      var salt;
      var rand = Math.round(Math.random() * 10);
      if ((rand % 2) === 0) {
        salt = ventoy_random_string(3);
      } else {
        salt = ventoy_random_string(4);
      }

      return 'md5#' + salt + '#' + md5(salt + pwd);
    }
  }

  function CommonPasswordEntry(tbl, name, cn, en) {
    var tr = '<tr><td>'+name+'</td><td><input type="password" class="form-control" id="id_'+name+'" disabled="disabled"/></td>' +
      '<td><button id="id_btn_set_'+name+'" class="btn btn-primary btn-sm btn-add CommPwdSetBtn"><span class="fa fa-edit"></span><span id="id_span_edit"></span></button>&nbsp;&nbsp;' +
      '<button id="id_btn_clr_'+name+'" class="btn btn-danger btn-sm btn-del CommPwdClearBtn"><span class="fa fa-trash"></span><span id="id_span_clear"></span></button></td>' +
      '<td><span id="id_span_desc_cn">' + cn + '</span>' +
      '<span id="id_span_desc_en">' + en + '</span></td>' +
      '</tr>';
    tbl.append(tr);
  }

  function FillCommonPassword(data) {
    var $tbl = $("#id_common_pwd tbody");
    $tbl.empty();

    CommonPasswordEntry($tbl, 'bootpwd', '启动进入 Ventoy 时的密码。', 'Password when Ventoy is booting.');
    CommonPasswordEntry($tbl, 'isopwd', '所有 .iso 文件的默认密码。', 'Default password for all .iso files.');
    CommonPasswordEntry($tbl, 'wimpwd', '所有 .wim 文件的默认密码。', 'Default password for all .wim files.');
    CommonPasswordEntry($tbl, 'imgpwd', '所有 .img 文件的默认密码。', 'Default password for all .img files.');
    CommonPasswordEntry($tbl, 'vhdpwd', '所有 .vhd(x) 文件的默认密码。', 'Default password for all .vhd(x) files.');
    CommonPasswordEntry($tbl, 'efipwd', '所有 .efi 文件的默认密码。', 'Default password for all .efi files.');
    CommonPasswordEntry($tbl, 'vtoypwd', '所有 .vtoy 文件的默认密码。', 'Default password for all .vtoy files.');

    $('input:password[id=id_bootpwd]').val(data.bootpwd);
    $('input:password[id=id_isopwd]').val(data.isopwd);
    $('input:password[id=id_wimpwd]').val(data.wimpwd);
    $('input:password[id=id_imgpwd]').val(data.imgpwd);
    $('input:password[id=id_efipwd]').val(data.efipwd);
    $('input:password[id=id_vhdpwd]').val(data.vhdpwd);
    $('input:password[id=id_vtoypwd]').val(data.vtoypwd);
  }

  function FillMenuPwdTable(data) {
    var addbtn = ventoy_get_xslg_addbtn('MenuPwdAddBtn');
    var delbtn = ventoy_get_xslg_delbtn('MenuPwdDelBtn');

    var td1, td2, td3, td4, td5, td6;
    var $tbl = $("#id_pwd_tbl tbody");
    $tbl.empty();

    for (var i = 0; i < data.length; i++) {
      var $tr;
      td1 = '<td>' + (i + 1) + '</td>';
      td2 = (data[i].type === 0) ? '<td>file</td>' : '<td>parent</td>';
      td3 = '<td>' + data[i].path + '</td>';
      td4 = '<td>' + ventoy_get_status_line(data[i].type, data[i].valid) + '</td>';
      td5 = '<td>' + data[i].pwd + '</td>';
      td6 = '<td>' + delbtn + '</td>';

      $tr = $('<tr>' + td1 + td2 + td3 + td4 + td5 + td6 + '</tr>');

      $tr.data('path', data[i].path);
      $tr.data('index', i);
      $tbl.append($tr);
    }

    $tbl.append('<tr><td></td><td></td><td></td><td></td><td></td><td>' + addbtn + '</td></tr>');
  }

  function VtoyFillCurrentPageItem(data) {
    FillCommonPassword(data);
    FillMenuPwdTable(data.list);
  }


  function OnClickMultiModeTab() {
    var href = $(this).attr('href');
    var index = parseInt(href.substr(5, 1));

    if (index < 0 || index >= g_vtoy_data_default_index || current_tab_index === index) {
      return;
    }
    
    current_tab_index = index;
    VtoyFillCurrentPageItem(m_data_pwd[index]);
  }

  function VtoyGetCurrentPageItem(data) {
    data.bootpwd = $('input:password[id=id_bootpwd]').val();
    data.isopwd = $('input:password[id=id_isopwd]').val();
    data.wimpwd = $('input:password[id=id_wimpwd]').val();
    data.imgpwd = $('input:password[id=id_imgpwd]').val();
    data.efipwd = $('input:password[id=id_efipwd]').val();
    data.vhdpwd = $('input:password[id=id_vhdpwd]').val();
    data.vtoypwd = $('input:password[id=id_vtoypwd]').val();
  }

  function VtoySaveCurrentPage() {
    VtoyGetCurrentPageItem(m_data_pwd[current_tab_index]);
    var data = m_data_pwd[current_tab_index];

    callVtoy({
      method : 'save_password',
      index: current_tab_index,
      bootpwd: data.bootpwd,
      isopwd: data.isopwd,
      wimpwd: data.bootpwd,
      imgpwd: data.imgpwd,
      efipwd: data.efipwd,
      vhdpwd: data.vhdpwd,
      vtoypwd: data.vtoypwd
    }, function(e) {
      Message.success(g_vtoy_cur_language.STR_SAVE_SUCCESS);
    });
  }

  var m_pwd_file_or_dir;
  var m_pwd_callback_func;
  var m_pwd_callback_data;
  var m_pwd_validator = $("#SetPwdForm").validate({    
    rules: {            
      PwdPath : {
          required: true,
          utfmaxlen: true
      },
      PwdPwd : {
          required: true,
          utfmaxlen: true,
          noquotes:true,
          printascii:true,
          maxlength: 40
      }
    },

    submitHandler: function(form) {
      var path = $('input:text[id=PwdPath]').val();
      var pwd = $('input:text[id=PwdPwd]').val();
      var type = parseInt($('input:radio[name=id_radio_pwd_type]:checked').val());

      if (m_pwd_validator.settings.rules.PwdPath.required) {
        path = ventoy_replace_slash(path);

        if (!ventoy_common_check_path(path)) {
            Message.error(g_vtoy_cur_language.STR_INVALID_FILE_PATH);
            return;
        }

        if (path.indexOf("*") >= 0) {
            callVtoySync({
                method : 'check_fuzzy',
                path: path
            }, function(data) {        
                if (data.exist != 0) {
                  if (typeof(m_pwd_callback_func) === 'function') {
                    m_pwd_callback_func(path, pwd, type, m_pwd_callback_data);
                  }
                    $("#SetPwdModal").modal('hide');
                } else {
                    Message.error(g_vtoy_cur_language.STR_INVALID_FILE_PATH);
                }
          });
        } else {

            callVtoySync({
                method : 'check_path',
                dir: m_pwd_file_or_dir,
                path: path
            }, function(data) {        
                if (data.exist === 1) {
                  if (typeof(m_pwd_callback_func) === 'function') {
                    m_pwd_callback_func(path, pwd, type, m_pwd_callback_data);
                  }
                  $("#SetPwdModal").modal('hide');
                } else {
                    Message.error(g_vtoy_cur_language.STR_INVALID_FILE_PATH);
                }
          });
        }
      } else {
        if (typeof(m_pwd_callback_func) === 'function') {
          
          m_pwd_callback_func(path, pwd, type, m_pwd_callback_data);
        }
        $("#SetPwdModal").modal('hide');
      }
    }
});

function VtoySetPassword(common, type, cb, data) {

    $('#SetPwdForm #SetPwdForm_title').text(g_vtoy_cur_language.STR_SET_PASSWORD);
    
    if (type === 0) {
      $('#SetPwdForm #SetPwdForm_path').text(g_vtoy_cur_language.STR_FILE_PATH);
    } else {
      $('#SetPwdForm #SetPwdForm_path').text(g_vtoy_cur_language.STR_DIR_PATH);
    }
    
    $('#SetPwdForm #SetPwdForm_pwd').text(g_vtoy_cur_language.STR_PASSWORD_VALUE);
    $('#SetPwdForm #SetPwdForm_type').text(g_vtoy_cur_language.STR_PASSWORD_TYPE);

    if (common) {
      m_pwd_validator.settings.rules.PwdPath.required = false;
      $('div[id=id_div_pwd_path]').hide();

    } else {
      m_pwd_validator.settings.rules.PwdPath.required = true;
      $('div[id=id_div_pwd_path]').show();

      if (type === 0) {
        if (g_current_language === 'en') {
          $('div[id=id_note_pwdfile_cn]').hide();
          $('div[id=id_note_pwdfile_en]').show();
        } else {
          $('div[id=id_note_pwdfile_cn]').show();
          $('div[id=id_note_pwdfile_en]').hide();
        }
        $('div[id=id_note_pwddir_cn]').hide();
        $('div[id=id_note_pwddir_en]').hide();
      } else {
        $('div[id=id_note_pwdfile_cn]').hide();
        $('div[id=id_note_pwdfile_en]').hide();
        if (g_current_language === 'en') {
          $('div[id=id_note_pwddir_cn]').hide();
          $('div[id=id_note_pwddir_en]').show();
        } else {
          $('div[id=id_note_pwddir_cn]').show();
          $('div[id=id_note_pwddir_en]').hide();
        }
      }
    }

    $('input:radio[name=id_radio_pwd_type]')[0].checked = true;

    if (g_current_language === 'en') {
        $('#SetPwdForm #SetPwdForm_ok').text(" OK");
        $('#SetPwdForm #SetPwdForm_cancel').text("Cancel");
    } else {
        $('#SetPwdForm #SetPwdForm_ok').text("确定");
        $('#SetPwdForm #SetPwdForm_cancel').text("取消");
    }
    
    m_pwd_file_or_dir = type;
    m_pwd_callback_func = cb;
    m_pwd_callback_data = data;
    m_pwd_validator.resetForm(); 
    $("#SetPwdModal").modal();            
}









  //Main process
  var m_data_pwd;
  var current_tab_index = 0;
  callVtoySync({method : 'get_password'}, function(data) {
    m_data_pwd = data;
  });
  
  function set_common_pwd_callback(path, pwd, type, data) {
    var selector = 'input:password[id=id_'+ data +']';
    var value = format_password(pwd, type);

    $(selector).val(value);
    VtoySaveCurrentPage();
  }
  $("#id_common_pwd").on('click', '.CommPwdSetBtn', function() {
    var id = $(this).attr('id');

    //id_btn_set_
    VtoySetPassword(1, 0, set_common_pwd_callback, id.substr(11));
  });
  $("#id_common_pwd").on('click', '.CommPwdClearBtn', function() {
    var id = $(this).attr('id');

    //id_btn_clr_
    var selector = 'input:password[id=id_'+ id.substr(11) +']';
    $(selector).val('');
    VtoySaveCurrentPage();
  });

  function set_menu_pwd_callback(path, pwd, type, FileOrDir) {
    var list = m_data_pwd[current_tab_index].list;
    var value = format_password(pwd, type);
    var valid = (path.indexOf("*") >= 0) ? -1 : 1;

    var data = {
      "type": FileOrDir,
      "path": path.substr(g_current_dir.length),
      "valid": valid,
      "pwd": value
    };

    for (var i = 0; i < list.length; i++) {
      if (list[i].path === data.path) {
        Message.error(g_vtoy_cur_language.STR_DUPLICATE_PATH);
        return;
      }
    }

    callVtoy({
      method : 'password_add',
      index: current_tab_index,
      type: data.type,
      path: data.path,
      pwd: data.pwd
    }, function(e) {
      if (e.result === 'success') {
        list.push(data);
        FillMenuPwdTable(list);
        Message.success(g_vtoy_cur_language.STR_SAVE_SUCCESS);
      } else if (e.result === 'duplicate') {
        Message.error(g_vtoy_cur_language.STR_DUPLICATE_PATH);
      }
    });

  }
  function OnAddMenuPwdBtnClick(sel)  {
    if (sel === 0) {
      var tip1 = (g_current_os === 'windows') ? '\\ISO\\Windows11.iso' : "/ISO/Ubuntu-20.04-desktop-amd64.iso";
      var tip2 = (g_current_os === 'windows') ? '\\ISO\\Windows**.iso' : "/ISO/Ubuntu-*****-desktop-amd64.iso";
      
      $('#SetPwdForm #id_span_pwdfile_tip1').text(g_current_dir + tip1);
      $('#SetPwdForm #id_span_pwdfile_tip2').text(g_current_dir + tip2);

      VtoySetPassword(0, 0, set_menu_pwd_callback, 0);

    } else {
      var tip = (g_current_os === 'windows') ? '\\ISO\\Windows' : "/ISO/Linux";
      $('#SetPwdForm #id_span_pwddir_tip').text(g_current_dir + tip);

      VtoySetPassword(0, 1, set_menu_pwd_callback, 1);

    }
  }

  $("#id_pwd_tbl").on('click', '.MenuPwdAddBtn', function() {
    var para = [
      {
        "selected": true,
        "tip": g_vtoy_cur_language.STR_SET_PWD_FOR_FILE
      },
      {
        "selected": false,
        "tip": g_vtoy_cur_language.STR_SET_PWD_FOR_DIR
      }
    ];

    VtoySelectType(OnAddMenuPwdBtnClick, para);
  });

  $("#id_pwd_tbl").on('click', '.MenuPwdDelBtn', function() {
    var $tr = $(this).closest('tr');
		var path = $tr.data('path');
    var index = $tr.data('index');

    callVtoySync({
        method : 'password_del',
        index: current_tab_index,
        path: path
    }, function(data) {
      m_data_pwd[current_tab_index].list.splice(index, 1);
      FillMenuPwdTable(m_data_pwd[current_tab_index].list);
      Message.success(g_vtoy_cur_language.STR_SAVE_SUCCESS);
    });
  });

  function VtoySaveCurrentPage() {
    var bootpwd = $('input:password[id=id_bootpwd]').val();
    var isopwd = $('input:password[id=id_isopwd]').val();
    var wimpwd = $('input:password[id=id_wimpwd]').val();
    var imgpwd = $('input:password[id=id_imgpwd]').val();
    var vhdpwd = $('input:password[id=id_vhdpwd]').val();
    var efipwd = $('input:password[id=id_efipwd]').val();
    var vtoypwd = $('input:password[id=id_vtoypwd]').val();

    callVtoy({
      method : 'save_password',
      index: current_tab_index,
      bootpwd: bootpwd,      
      isopwd: isopwd,
      wimpwd: wimpwd,
      imgpwd: imgpwd,
      vhdpwd: vhdpwd,
      efipwd: efipwd,
      vtoypwd: vtoypwd
    }, function(e) {
      Message.success(g_vtoy_cur_language.STR_SAVE_SUCCESS);
    });
  }

  $('input:password[id=id_bootpwd]').change(VtoySaveCurrentPage);
  $('input:password[id=id_isopwd]').change(VtoySaveCurrentPage);
  $('input:password[id=id_wimpwd]').change(VtoySaveCurrentPage);
  $('input:password[id=id_imgpwd]').change(VtoySaveCurrentPage);
  $('input:password[id=id_vhdpwd]').change(VtoySaveCurrentPage);
  $('input:password[id=id_efipwd]').change(VtoySaveCurrentPage);
  $('input:password[id=id_vtoypwd]').change(VtoySaveCurrentPage);

  $('#id_tab_password a[href="#tab_0"]').click(OnClickMultiModeTab);
  $('#id_tab_password a[href="#tab_1"]').click(OnClickMultiModeTab);
  $('#id_tab_password a[href="#tab_2"]').click(OnClickMultiModeTab);
  $('#id_tab_password a[href="#tab_3"]').click(OnClickMultiModeTab);
  $('#id_tab_password a[href="#tab_4"]').click(OnClickMultiModeTab);
  $('#id_tab_password a[href="#tab_5"]').click(OnClickMultiModeTab);

  function UpdateTabTitleIcon(data) {
    CommonUpdateTabTitleIcon(data.exist_password, '#id_tab_password a[href="#tab_', 'password');
  }
  $('#id_btn_reset').click(function() { 
    Modal.confirm({msg:GetResetTabConfigTipMsg(current_tab_index, 'password')}).on(function(e) {
        if (e) {            
            callVtoySync({
                method : 'password_del',
                index: current_tab_index,
                path: g_del_all_path
            }, function(data) {
                
            });
            
            m_data_pwd[current_tab_index].list.length = 0;
            VtoyFillCurrentPageItem(m_data_pwd[g_vtoy_data_default_index]);
            VtoySaveCurrentPage();
        }
    });
  });

  $('#id_tab_password a[href="#tab_0"]').tab('show');
  VtoyFillCurrentPageItem(m_data_pwd[0]);
  VtoyPageLanguageChange(g_current_language);

</script>
